package manage.service;

import m.common.model.util.ModelQueryUtil;
import m.common.model.util.ModelUpdateUtil;
import m.common.service.Service;
import m.system.db.DBManager;
import m.system.db.DataRow;
import m.system.db.TransactionManager;
import manage.model.ServerSetting;

import java.util.Date;

public class ServerSettingService extends Service {

	private static ServerSetting serverSetting=null;
	/**
	 * 获取唯一的model
	 * 
	 *  Exception
	 */
	public ServerSetting getUniqueModel() throws Exception{
		if(null==serverSetting){
			DataRow dr=DBManager.queryFirstRow("SELECT oid FROM os_server_setting");
			ServerSetting ps=new ServerSetting();
			if(null==dr){
				ps.setOid("1");
				ps.setRequestMonitor("N");
				ps.setRecordDuration("A");
				ps.setSaveDuration("A");
				ModelUpdateUtil.insertModel(ps);
			}else{
				ps.setOid(dr.get(String.class,"oid"));
			}
			serverSetting=ModelQueryUtil.getModel(ps);
		}
		return serverSetting;
	}
	public String save(ServerSetting model) throws Exception {
		ModelUpdateUtil.updateModel(model);
		serverSetting=null;
		getUniqueModel();
		return "保存成功";
	}
	
	public void deleteAllRecord() {
		TransactionManager tm=new TransactionManager();
		try {
			tm.begin();
			DBManager.executeUpdate("delete from os_server_host");
			DBManager.executeUpdate("delete from os_server_request");
			DBManager.executeUpdate("delete from os_server_request_d");
			tm.commit();
		} catch (Exception e) {
			tm.rollback();
			e.printStackTrace();
		}
	}
	public void deleteRecord(Date date) {
		TransactionManager tm=new TransactionManager();
		try {
			tm.begin();
			DBManager.executeUpdate("delete from os_server_request where server_host_oid in(select oid from os_server_host where log_date<?)", date);
			DBManager.executeUpdate("delete from os_server_request_d where log_date<?", date);
			DBManager.executeUpdate("delete from os_server_host where end_date<?", date);
			tm.commit();
		} catch (Exception e) {
			tm.rollback();
			e.printStackTrace();
		}
	}
}
